﻿/********************************************************************
	日期:2022/4/28 21:10
	名称:GameRoot
	邮箱:yunnibbd@163.com
	作者:yunni
	描述:服务初始化
*********************************************************************/

using System;
using System.Collections.Generic;
using PEProtocol;

public class ServerRoot{
    private static ServerRoot instance = null;

    public static ServerRoot Instance{
        get{
            if (instance == null){
                instance = new ServerRoot();
            }

            return instance;
        }
    }

    public void Init(){
        //数据库TODO
        DBMgr.Instance.Init();
        //服务层
        CfgSvc.Instance.Init();
        NetSvc.Instance.Init();
        CacheSvc.Instance.Init();
        TimerSvc.Instance.Init();

        //业务系统
        LoginSys.Instance.Init();
        GuideSys.Instance.Init();
        StrongSys.Instance.Init();
        ChatSys.Instance.Init();
        BuySys.Instance.Init();
        PowerSys.Instance.Init();
        TaskSys.Instance.Init();
        FuBenSys.Instance.Init();
        
        //开启心跳
        this.StartHeart();
    }

    public void Update(){
        NetSvc.Instance.Update();
        TimerSvc.Instance.Update();
    }

    private int SessionID = 0;

    public int GetSessionID(){
        if (SessionID == int.MaxValue){
            SessionID = 0;
        }

        return SessionID += 1;
    }

    /// <summary>
    /// 开启所有客户端的心跳计时
    /// </summary>
    public  void StartHeart(){
        TimerSvc.Instance.AddTimerTask((int tid) => {
            PECommon.Log("check heart start...");
            List<ServerSession> onlineServerSessions = CacheSvc.Instance.GetOnlineServerSessions();
            for (int i = 0; i < onlineServerSessions.Count; i++){
                onlineServerSessions[i].CheckHeart(5);
            }
            PECommon.Log("check heart end...");
        }, 5000, PETimeUnit.Millisecond, -1);
    }
    
    /// <summary>
    /// 对收到心跳包的客户端进行心跳计时置0
    /// </summary>
    /// <param name="pkt"></param>
    public static void ReqHeart(MsgPack pkt){
        pkt.session.ResetHeart();
    }
}
